<?php
declare (strict_types=1);

namespace app\index\controller;

use app\BaseController;
use app\common\model\Room as RoomModel;
use app\common\model\Comment as CommentModel;
use think\Request;


class Room extends BaseController
{
    //客房列表
    public function index(Request $request)
    {
        //客房名称
        $name = $request->get("name", '') ?: '';
        $page = $request->get("page", 1) ?: 1;
        $roomList = RoomModel::select()->toArray();

        //客房查询
        if (!empty($name)) {
            $roomList = array_filter($roomList, function ($room) use ($name) {
                return str_contains($room['name'], $name);
            });
        }

        //分页数据
        $size = 8;
        $total = count($roomList);
        $totalPage = ceil(count($roomList) / $size);
        $roomList = array_slice($roomList, ($page - 1) * $size, $size);

        $roomChunkList = array_chunk($roomList, 4);

        return view('room/index', [
            'roomChunkList' => $roomChunkList,
            'total' => $total,
            'totalPage' => $totalPage,
            'page' => $page
        ]);
    }

    //客房详情
    public function detail($id) {
        $room = RoomModel::find($id);
        $commentList = CommentModel::where('room_id', $id)->select();
        return view('room/detail', ['room' => $room, 'commentList' => $commentList]);
    }

    //预定
    public function reserve($id) {
        if (empty(session('user'))) {
            $this->redirect('/login');
        }

        $room = RoomModel::find($id);
        $room['room_numbers'] = explode(',', $room['room_numbers']);
        return view('room/reserve', ['room' => $room]);
    }
}
